package com.pig4cloud.pig.module.controller.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.product.WarmHeartCashRecord;
import com.pig4cloud.pig.module.api.entity.wx.WxUser;
import com.pig4cloud.pig.module.service.product.IWarmHeartCashRecordService;
import com.pig4cloud.pig.module.service.wx.IWxUserService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;

/**
 * 暖心宝上传记录，打款记录Controller
 *
 * @author ruoyi
 * @date 2022-10-28
 */
@Validated
@Api(value = "暖心宝上传记录，打款记录控制器", tags = {"暖心宝上传记录，打款记录管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/warm/heart/record")
public class WarmHeartCashRecordController {

    private final IWarmHeartCashRecordService warmHeartCashRecordService;
	private final IWxUserService wxUserService;
//	private final ISysConfigService sysConfigService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

    /**
     * 查询暖心宝上传记录，打款记录列表
     */
    @ApiOperation("查询暖心宝上传记录，打款记录列表")
    @PreAuthorize("@pms.hasPermission('module:warmHeartRecord:list')")
    @GetMapping("/list")
    public TableDataInfo<WarmHeartCashRecord> list(@Validated WarmHeartCashRecord warmHeartCashRecord) {
        QueryWrapper<WarmHeartCashRecord> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(warmHeartCashRecord.getOrderNo())){
        	qw.like("order_no",warmHeartCashRecord.getOrderNo())
				.or().like("phone_num",warmHeartCashRecord.getOrderNo());
		}

		if(StrUtil.isNotEmpty(warmHeartCashRecord.getBeginDate())){
			qw.between("create_time",warmHeartCashRecord.getBeginDate() + " 00:00:00",warmHeartCashRecord.getEndDate() + " 23:59:59");
		}
		qw.orderByDesc("create_time");

		TableDataInfo<WarmHeartCashRecord> td = PageUtils.buildDataInfo(warmHeartCashRecordService.page(PageUtils.buildPage(),qw));
        List<WarmHeartCashRecord> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for (WarmHeartCashRecord record : list){
				WxUser wxUser = wxUserService.findById(record.getUserId());
				if(wxUser!=null){
					if(StrUtil.isNotEmpty(wxUser.getNickName())){
						record.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
					}

					record.setFaceUrl(wxUser.getFaceUrl());
					if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
						record.setFaceUrl(imgUrl + wxUser.getFaceUrl());
					}
				}
				if(StrUtil.isNotEmpty(record.getImgUrl())){
					record.setImgUrlPath(imgUrl + record.getImgUrl());
				}
			}
		}

        Map<String,Object> map = new HashMap<>();
		if(StrUtil.isNotEmpty(warmHeartCashRecord.getBeginDate())){
			map.put("begin_time",warmHeartCashRecord.getBeginDate() + " 00:00:00");
			map.put("end_time",warmHeartCashRecord.getEndDate() + " 23:59:59");
		}
		WarmHeartCashRecord tongjiRecord =  warmHeartCashRecordService.selectTongji(map);
        map.put("tongji",tongjiRecord);
        td.setOtherData(map);

        return td;
    }

    /**
     * 导出暖心宝上传记录，打款记录列表
     */
    @ApiOperation("导出暖心宝上传记录，打款记录列表")
    @PreAuthorize("@pms.hasPermission('module:warmHeartRecord:export')")
    @SysLog("暖心宝上传记录，打款记录")
    @GetMapping("/export")
    public List export(@Validated WarmHeartCashRecord warmHeartCashRecord) {
        List<WarmHeartCashRecord> list = warmHeartCashRecordService.list();
        // ExcelUtil<WarmHeartCashRecord> util = new // ExcelUtil<>(WarmHeartCashRecord.class);
        return  list;// util.exportExcel(list, "暖心宝上传记录，打款记录");
    }

    /**
     * 获取暖心宝上传记录，打款记录详细信息
     */
    @ApiOperation("获取暖心宝上传记录，打款记录详细信息")
    @PreAuthorize("@pms.hasPermission('module:warmHeartRecord:query')")
    @GetMapping("/{id}")
    public R<WarmHeartCashRecord> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {

//		String regBagMoney = sysConfigService.selectConfigByKey("warm.heart.reg_bag");
        WarmHeartCashRecord record = warmHeartCashRecordService.getById(id);
        if(record!=null){
			WxUser wxUser = wxUserService.findById(record.getUserId());
			if(wxUser!=null){
				if(StrUtil.isNotEmpty(wxUser.getNickName())){
					record.setNickName(EmojiParser.parseToUnicode(wxUser.getNickName()));
				}
				record.setFaceUrl(wxUser.getFaceUrl());
				if(StrUtil.isNotEmpty(wxUser.getFaceUrl()) && wxUser.getFaceUrl().indexOf("https") < 0) {
					record.setFaceUrl(imgUrl + wxUser.getFaceUrl());
				}
			}

			if(StrUtil.isNotEmpty(record.getImgUrl())){
				record.setImgUrlPath(imgUrl + record.getImgUrl());
			}
//			record.setPayMoney(new BigDecimal(regBagMoney));
		}
        return R.ok(record);
    }

    /**
     * 新增暖心宝上传记录，打款记录
     */
    @ApiOperation("新增暖心宝上传记录，打款记录")
    @PreAuthorize("@pms.hasPermission('module:warmHeartRecord:add')")
    @SysLog("暖心宝上传记录，打款记录")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody WarmHeartCashRecord warmHeartCashRecord) {
        return R.okByRow(warmHeartCashRecordService.save(warmHeartCashRecord) ? 1 : 0);
    }

    /**
     * 修改暖心宝上传记录，打款记录
     */
    @ApiOperation("修改暖心宝上传记录，打款记录")
    @PreAuthorize("@pms.hasPermission('module:warmHeartRecord:edit')")
    @SysLog("暖心宝上传记录，打款记录")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody WarmHeartCashRecord warmHeartCashRecord) {
		PigUser sysUser = SecurityUtils.getUser();
		warmHeartCashRecord.setCheckSysUserId(sysUser.getId());
		warmHeartCashRecord.setCheckSysUserName(sysUser.getName());
		warmHeartCashRecord.setCheckTime(new Date());
		boolean bl = false;
		if(warmHeartCashRecord.getCheckState() == 1){
			Map<String,Object> map = warmHeartCashRecordService.checkRecord(warmHeartCashRecord);
			if(map.containsKey("result_code")){
				if(map.get("result_code").equals("SUCCESS")){
					return R.okByRow(1);
				} else {
					return R.failed(map.get("err_code_des").toString());
				}
			}
			return R.okByRow(0);
		}else{
			bl = warmHeartCashRecordService.updateById(warmHeartCashRecord);
		}
		return R.okByRow(bl ? 1 : 0);
    }


	/**
	 * 批量重新打款
	 */
	@ApiOperation("批量重新打款")
	@PreAuthorize("@pms.hasPermission('module:signRecord:remove')")
	@SysLog("批量重新打款")
	@DeleteMapping("/repay/{ids}")
	public R<Void> repay(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
		boolean bl = false;
		for (Long id  : ids){
			WarmHeartCashRecord warmHeartCashRecord = warmHeartCashRecordService.findById(id);
			if(warmHeartCashRecord!=null){
				if(warmHeartCashRecord.getPayMoney().doubleValue() > 0 && (warmHeartCashRecord.getPayState() == 0 || warmHeartCashRecord.getPayState() == 2)){
					int ret = warmHeartCashRecordService.resetCash(warmHeartCashRecord);
					if(ret > 0){
						bl = true;
					}
				}
			}
		}
		return R.okByRow(bl ? 1 : 0);
	}


	/**
     * 删除暖心宝上传记录，打款记录
     */
    @ApiOperation("删除暖心宝上传记录，打款记录")
    @PreAuthorize("@pms.hasPermission('module:warmHeartRecord:remove')")
    @SysLog("暖心宝上传记录，打款记录")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(warmHeartCashRecordService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
